#include "../include/EchoServer.h"
#include "../include/userMananger.hpp"

namespace rocket 
{

EchoServer::EchoServer(unsigned short port, 
               const string & ip ,
               size_t threadNum ,
               size_t queSize )
: _server(port,ip)
, _threadpool(threadNum, queSize)
{
    using namespace std::placeholders;
    _server.setAllCallbacks(
                            std::bind(&EchoServer::onConnection, this, _1),
                            std::bind(&EchoServer::onMessage, this, _1),
                            std::bind(&EchoServer::onClose, this, _1)
                           );
}


void EchoServer::start()
{
    _threadpool.start();
    _server.start();
}
//处理已经新建立的链接的业务
void EchoServer::onConnection(wd::TcpConnectionPtr conn)
{
    //打印一个新连接的五元组信息
    cout << conn->toString() << " has connected successfully" << endl;
}

//处理已经建立的链接的业务
void EchoServer::onMessage(wd::TcpConnectionPtr conn)
{
    wd::Packet packet;
    if (conn->readPacket(packet)==false) 
    {
        cout << "读取 TLV 失败，关闭连接" << endl;
        conn->shutdown();
        return;
    }

    // 根据TLV类型分发任务
switch (packet._type) 
{
   //注册阶段1，接收用户名并查重，根据结果返回盐值
    case TASK_TYPE_REGISTER_SECTION1: 
    {  
        rocket::UserRegisterSection1 task(packet, conn);
        _threadpool.addTask(std::bind(&rocket::UserRegisterSection1::process, task));
        break;
    }
   //注册阶段2，接收密文并存到对应用户的数据库记录中
    case TASK_TYPE_REGISTER_SECTION2: 
    {
        rocket::UserRegisterSection2 task(packet, conn);
        _threadpool.addTask(std::bind(&rocket::UserRegisterSection2::process, task));
        break;
    }
   //登录阶段1，接收用户名并查找，并根据结果返回盐值
    case TASK_TYPE_LOGIN_SECTION1: 
    {
        rocket::UserLoginSection1 task(packet, conn);
        _threadpool.addTask(std::bind(&rocket::UserLoginSection1::process, task));
        break;
    }
   //登录阶段2，接收密文并比对，返回比对结果
    case TASK_TYPE_LOGIN_SECTION2: 
    {
        rocket::UserLoginSection2 task(packet, conn);
        _threadpool.addTask(std::bind(&rocket::UserLoginSection2::process, task));
        break;
    }
}
}

//处理已经要关闭链接的业务
void EchoServer::onClose(wd::TcpConnectionPtr conn)
{
    //将用户从userMananger中移除
    rocket::userMananger::get_instance()->delete_user(conn->getfd());
    cout << conn->toString() << " has closed." << endl;
}

}//end of namespace rocket
